/*
 * @Author: zhang zhijiang 2824735304@qq.com
 * @Date: 2025-04-24 20:41:01
 * @LastEditors: zhang zhijiang 2824735304@qq.com
 * @LastEditTime: 2025-04-25 21:46:00
 * @FilePath: /linux/tcpcalculator/protocol.hpp
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#pragma once
#include<cstring>
#include<iostream>
#include<cstring>
using namespace std;
using std::cout;
using std::endl;
 static char blank_space_sep = ' ';
 static char line_sep = '\n';
 //"x + y"
 std::string Encode(std::string content)//序列化之后进行网络化
 {
    size_t len = content.size();
    std::string s = std::to_string(len);
    s+=line_sep;
    s+=content;
    s+=line_sep;
    
    return s;
 }
 //"len\n""x + y"\n
 bool Decode(std::string& package,std::string & content)
 {
    int pos = package.find(line_sep);
    if(pos==package.npos) return false;
    std::string len_str = package.substr(0,pos);
    size_t len = stoi(len_str);
    //package = len_str+2+content.std
    int total_len = 2+ len + len_str.size();
    if(package.size()<total_len)
    return false;
    content = package.substr(pos+1,len);
    //cout << content << endl;
    //移除
    package.erase(0,total_len);
    return true;
 }
class request
{
    public:
    request(int _x,int _y,char _op):x(_x),y(_y),op(_op)
    {}
    request()
    {}
    ~request()
    {

    }//"x + y"
    bool  serialize(std::string &out)
    {
        std::string s = std::to_string(x);
        s+=blank_space_sep;
        s+=op;
        s+=blank_space_sep;
        s+= std::to_string(y);
        out = s;
        return true;
    }
    //"x + y"
    bool deserialize(std::string& in )
    {
        size_t left = in.find(blank_space_sep);
        if(left==in.npos) return false;
        x =stoi(in.substr(0,left++));
        size_t right = in.rfind(blank_space_sep);
        if(right==0) return false;
        y = stoi(in.substr(right++));
        op = in[left];
        
        return true;
    }
    public:
    int x;
    int y;
    char op;
};
class response
{
    public:
    response(int _r,int c):result(_r),code(c)
    {

    }
    response()
    {}
    // "result code"
    bool  serialize(std::string &out)
    {
        std::string s = std::to_string(result);
        s+=blank_space_sep;
        s+= std::to_string(code);
        out = s;
        return true;
    }
    //"result code"
    bool deserialize(std::string& in )
    {
        size_t pos = in.find(blank_space_sep);
        if(pos==in.npos) return false;
        result =stoi(in.substr(0,pos));
        code = stoi(in.substr(pos + 1));

        return true;
    }

    ~response()
    {

    }
    public:
    int result;
    int code;
};